package org.black.phoneUtility.sms.reply.app.service;

import java.util.ArrayList;
import java.util.List;

import org.black.phoneUtility.R;
import org.black.phoneUtility.sms.reply.appwidget.SmsReplyAppWidgetProvider;
import org.black.phoneUtility.sms.reply.provider.SmsReplyContract;
import org.black.phoneUtility.sms.reply.service.SmsReplyService;
import org.black.phoneUtility.sms.reply.service.exception.NoPhoneMessageException;
import org.black.phoneUtility.sms.reply.service.exception.NoReplyMessageException;
import org.black.phoneUtility.sms.reply.service.exception.NoSmsMessageException;
import org.black.phoneUtility.sms.reply.service.exception.ReplyDateTimeExpiredException;
import org.black.phoneUtility.sms.reply.service.exception.ReplyDateTimeInvalidException;
import org.black.phoneUtility.sms.reply.service.exception.SmsReplyNotExistException;

import android.app.IntentService;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

public class SmsReplyAppWidgetSwitchStatusService extends IntentService {
	private static final String LOG_TAG = SmsReplyAppWidgetSwitchStatusService.class
			.getName();
	public static final String ARGUMENTS_SMS_REPLY_ID = "arguments_sms_reply_id";

	private Handler handler;
	private SmsReplyService smsReplyService;

	public SmsReplyAppWidgetSwitchStatusService() {
		super(SmsReplyAppWidgetSwitchStatusService.class.getName());
	}

	@Override
	public void onCreate() {
		super.onCreate();
		this.handler = new ToastHandler(getMainLooper());
		this.smsReplyService = new SmsReplyService(this);
		Log.i(LOG_TAG, "Create " + LOG_TAG);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		this.handler = null;
		this.smsReplyService = null;
		Log.i(LOG_TAG, "Destory " + LOG_TAG);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
		Bundle extras = intent.getExtras();
		if (extras != null) {
			appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);
		}
		if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
			Log.e(LOG_TAG, "appWidgetId is invalid!");
			return;
		}

		long smsReplyId = 0l;
		Cursor cursor = null;
		String title = null;

		List<Integer> appwidgetIds = new ArrayList<Integer>();
		try {
			// TODO: when sms reply id is invalid
			cursor = this
					.getContentResolver()
					.query(SmsReplyContract.SmsReplyAppWidgetIds.CONTENT_URI,
							new String[] { SmsReplyContract.SmsReplyAppWidgetIds.REFERENCE_SMS_REPLY_ID },
							SmsReplyContract.SmsReplyAppWidgetIds.APP_WIDGET_ID
									+ " = ? ",
							new String[] { String.valueOf(appWidgetId) }, null,
							null);
			if (cursor.moveToFirst() == true) {
				smsReplyId = cursor
						.getLong(cursor
								.getColumnIndex(SmsReplyContract.SmsReplyAppWidgetIds.REFERENCE_SMS_REPLY_ID));
			}
			cursor.close();
			cursor = this.getContentResolver().query(
					SmsReplyContract.SmsReplies.CONTENT_URI,
					new String[] { SmsReplyContract.SmsReplies.TITLE },
					SmsReplyContract.SmsReplies._ID + " = ? ",
					new String[] { String.valueOf(smsReplyId) }, null, null);
			if (cursor.moveToFirst() == true) {
				title = cursor.getString(cursor
						.getColumnIndex(SmsReplyContract.SmsReplies.TITLE));
			}
			cursor.close();
			cursor = this
					.getContentResolver()
					.query(SmsReplyContract.SmsReplyAppWidgetIds.CONTENT_URI,
							new String[] { SmsReplyContract.SmsReplyAppWidgetIds.APP_WIDGET_ID },
							SmsReplyContract.SmsReplyAppWidgetIds.REFERENCE_SMS_REPLY_ID
									+ " = ?",
							new String[] { String.valueOf(smsReplyId) }, null,
							null);
			if (cursor.moveToFirst() == true) {
				do {
					appwidgetIds
							.add(cursor.getInt(cursor
									.getColumnIndex(SmsReplyContract.SmsReplyAppWidgetIds.APP_WIDGET_ID)));
				} while (cursor.moveToNext() == true);
			}
		} catch (Throwable throwable) {
			Log.e(LOG_TAG, "Unknown Error!", throwable);
		} finally {
			if (cursor != null) {
				try {
					cursor.close();
				} catch (Throwable th) {
					Log.e(LOG_TAG, "Fail to close cursor", th);
				}
			}
		}

		boolean isActivated = false;

		try {
			isActivated = smsReplyService.switchSmsReplyActivateStatus(smsReplyId);
		} catch (NoPhoneMessageException e) {
			Log.e(LOG_TAG, e.getMessage(), e);
			Message hanMessage = handler.obtainMessage();
			hanMessage.what = ToastHandler.WHAT_NO_PHONE_MESSAGE;
			handler.sendMessage(hanMessage);
			return;
		} catch (NoReplyMessageException e) {
			Log.e(LOG_TAG, e.getMessage(), e);
			Message hanMessage = handler.obtainMessage();
			hanMessage.what = ToastHandler.WHAT_NO_REPLY_MESSAGE;
			handler.sendMessage(hanMessage);
			return;
		} catch (NoSmsMessageException e) {
			Log.e(LOG_TAG, e.getMessage(), e);
			Message hanMessage = handler.obtainMessage();
			hanMessage.what = ToastHandler.WHAT_NO_SMS_MESSAGE;
			handler.sendMessage(hanMessage);
			return;
		} catch (ReplyDateTimeInvalidException e) {
			Log.e(LOG_TAG, e.getMessage(), e);
			Message hanMessage = handler.obtainMessage();
			hanMessage.what = ToastHandler.WHAT_DATE_TIME_INVALID_MESSAGE;
			handler.sendMessage(hanMessage);
			return;
		} catch (SmsReplyNotExistException e) {
			Log.e(LOG_TAG, e.getMessage(), e);
			Message hanMessage = handler.obtainMessage();
			hanMessage.what = ToastHandler.WHAT_NOT_EXIST_MESSAGE;
			handler.sendMessage(hanMessage);
			return;
		} catch (ReplyDateTimeExpiredException e) {
			Log.e(LOG_TAG, e.getMessage(), e);
			Message hanMessage = handler.obtainMessage();
			hanMessage.what = ToastHandler.WHAT_DATE_TIME_EXPIRED_MESSAGE;
			handler.sendMessage(hanMessage);
			return;
		} catch (RemoteException e) {
			Log.e(LOG_TAG, e.getMessage(), e);
		} catch (OperationApplicationException e) {
			Log.e(LOG_TAG, e.getMessage(), e);
		}
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
		for (Integer appId : appwidgetIds) {
			SmsReplyAppWidgetProvider.updateAppWidget(this, appWidgetManager,
					smsReplyId, appId, isActivated, title);
		}

	}

	class ToastHandler extends Handler {
		public static final int WHAT_NO_REPLY_MESSAGE = 129;
		public static final int WHAT_NO_PHONE_MESSAGE = 130;
		public static final int WHAT_NO_SMS_MESSAGE = 131;
		public static final int WHAT_DATE_TIME_EXPIRED_MESSAGE = 132;
		public static final int WHAT_DATE_TIME_INVALID_MESSAGE = 133;
		public static final int WHAT_NOT_EXIST_MESSAGE = 134;

		public ToastHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			int what = msg.what;
			String text = "";
			switch (what) {
			case WHAT_NO_REPLY_MESSAGE:
				text = getString(R.string.sms_reply_error_no_reply_message);
				break;
			case WHAT_NO_PHONE_MESSAGE:
				text = getString(R.string.sms_reply_error_no_phone_message);
				break;
			case WHAT_NO_SMS_MESSAGE:
				text = getString(R.string.sms_reply_error_no_sms_message);
				break;
			case WHAT_DATE_TIME_EXPIRED_MESSAGE:
				text = getString(R.string.sms_reply_error_reply_date_time_has_expired);
				break;
			case WHAT_DATE_TIME_INVALID_MESSAGE:
				text = getString(R.string.sms_reply_error_reply_date_time_is_invalid);
				break;
			case WHAT_NOT_EXIST_MESSAGE:
				text = getString(R.string.sms_reply_error_not_exist_please_remove_this_widget);
				break;
			default:
				break;
			}
			Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT)
					.show();
		}
	}
}
